﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace OSCFill
{
    public delegate void DisplayMessage(string str);
    public partial class Form1 : Form
    {
        DisplayMessage showMsg = null;
        private string path="";
        int count = 0;
        bool istop = true;
        public Form1()
        {
            InitializeComponent();
        }

        private void btBrowser_Click(object sender, EventArgs e)
        {
            if (fbdFind.ShowDialog(this) == DialogResult.OK)
            {
                tbFilePath.Text = fbdFind.SelectedPath;
            }
        }

        private void ShowMsg(string msg)
        {
            tbMessage.AppendText(DateTime.Now.ToString()+":"+msg+"\r\n");
        }

        private void btFind_Click(object sender, EventArgs e)
        {
            path = tbFilePath.Text;
            if (path == "") return;
            
            count = 0;
            Thread th = new Thread(new ParameterizedThreadStart(DealFind));
            th.Start(path);

        }
        private void DealFind(object oo)
        {
            var spath = oo.ToString();
            FindPath(spath);
            if (count == 0)
            {
                this.Invoke(showMsg, "没有发现空文件夹");
            }
            else
            {
                this.Invoke(showMsg, "共发现"+count+"个空文件夹");
            }
        }

        private void FindPath(string spath)
        {
            
            var dirs = Directory.GetDirectories(spath);
            if (dirs.Length > 0)
            {
                foreach (var dir in dirs)
                {
                    FindPath(dir);
                }
            }
            else
            {
                var files = Directory.GetFiles(spath);
                if (files.Length == 0)
                {
                    count++;
                    if (cbFill.Checked)
                    {
                        var fc=File.CreateText(spath + "\\x.keep");
                        fc.Close();
                    }
                    this.Invoke(showMsg, spath);
                }
            }
            
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            showMsg = new DisplayMessage(ShowMsg);
        }
    }
}
